package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private IServiceItemService serviceItemService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    //上架
    public void saleOn(Long id) {
        //通过id查询数据库获取该服务单项
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        //判断该服务单项是否是套餐，如果是则需要审核；如果是在审核状态则不能上架
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            throw new BusinessException("该服务是套餐需要等待审核，不能上架！");
        }else if(ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("该服务还在审核中，不能上架！");
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_ON);
        serviceItemMapper.updateSaleStatus(serviceItem);
    }

    //下架
    public void saleOff(Long id) {
        //查出该服务单项
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(id);
        //判断该服务是否是套餐，如果是则修改审核状态为初始化；否则就修改为下架状态
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
            serviceItemMapper.updateAuditStatus(serviceItem);
        }
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateSaleStatus(serviceItem);
    }

    //开始审核：启动流程+创建添加流程审核记录表
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
        //1、首先判断该服务单项是否满足审核条件
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(serviceItemId);
        if(ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
                || !ServiceItem.AUDITSTATUS_INIT.equals(serviceItem.getAuditStatus())){//服务单项状态必须是套餐+初始化
            throw new BusinessException("服务单项不满足审核条件！");
        }
        //修改服务单项状态为审核中
        serviceItemService.updateStatus(serviceItemId,ServiceItem.AUDITSTATUS_AUDITING);
        //2、创建并添加流程审核记录表
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setServiceItemId(serviceItemId);
        carPackageAudit.setServiceItemPrice(serviceItem.getDiscountPrice());
        carPackageAudit.setServiceItemInfo(serviceItem.getInfo());
        carPackageAudit.setCreateTime(serviceItem.getCreateTime());

        carPackageAudit.setCreator(ShiroUtils.getUser().getUserName());//一般为登录系统的客服等等
        carPackageAudit.setBpmnInfoId(bpmnInfoId);
        carPackageAudit.setAuditorId(director);//起初审核的人是店长角色的某位负责人
        carPackageAudit.setInfo(info);
        carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);//当前流程审核记录表的状态:审核中
        carPackageAuditMapper.insert(carPackageAudit);
        //3、使用activiti启动流程(主要是获取businessKey，业务)
        String businessKey=carPackageAudit.getId().toString();//利用上一步插入成功后返回的主键
        Map<String,Object> varibles=new HashMap<>();//负责指定任务节点负责人+流程变量
        varibles.put("director",director);//传过来的指定的店长负责人id
        varibles.put("finance",finance);
        varibles.put("discountPrice",serviceItem.getDiscountPrice().longValue());//注意必须转为long,没有Bigdecimal类型

        //获取自定义流程定义信息bpmninfo
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(bpmnInfoId);
        ProcessInstance processInstance = runtimeService
                .startProcessInstanceByKey(bpmnInfo.getActProcessKey(), businessKey, varibles);
        //流程启动后，需要重新修改流程审核记录表
        carPackageAuditMapper.updateInstanceId(carPackageAudit.getId(),processInstance.getProcessInstanceId());
    }

    //修改服务单项状态
    public void updateStatus(Long serviceItemId, Integer auditstatusInit) {
        serviceItemMapper.updateStatus(serviceItemId,auditstatusInit);
    }

}
